import { View } from '@tarojs/components'
import Taro, { Component } from '@tarojs/taro'
import classNames from 'classnames'

import config from '../../../config'

// styles
import './AuthView.scss'

// components
import Authorize from '../AuthorizeInfo'

// models

// services

// api
// import * as miniProgramApi from '../../apis/miniProgramApi'

export interface DataProps {}
export interface EventProps {
  onReady?: () => any
}
export type Props = DataProps & EventProps

interface State {
  loading: boolean
  isOpened: boolean
  miniProgramInfo: any
}
export default class AuthView extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
      loading: true,
      isOpened: false,
      miniProgramInfo: {},
    }
  }

  componentDidMount() {
    this.wxAuthorize()
  }

  // 检查是否已经微信授权
  wxAuthorize = async () => {
    Taro.showLoading({ title: '加载中...', mask: true })

    const res = await Taro.getSetting()
    // 是否授权过，同意或拒绝
    const hasAuth = 'scope.userInfo' in res.authSetting
    // 是否已同意
    const isAgree = res.authSetting['scope.userInfo']
    let needAuth = !hasAuth

    // 非线上时，未授权或已拒绝都提示用户授权，为了方便调试
    if (!config.online) {
      needAuth = !isAgree
    }

    if (needAuth) {
      // config.appId
      this.setState({
        isOpened: true,
        loading: false,
      })
      Taro.hideTabBar({ animation: false })
      Taro.hideLoading()
      return
    }

    this.setState(
      {
        isOpened: false,
        loading: false,
      },
      async () => {
        this.ready()
      },
    )
  }

  // 点击完成微信授权
  onClickAuthorize = async (userInfo: Authorize.UserInfo) => {
    Taro.showLoading({ title: '加载中...', mask: true })

    this.updateInfo(userInfo)

    this.setState(
      {
        isOpened: false,
      },
      () => {
        this.ready()
      },
    )
  }

  /**
   * 更新资料
   */
  async updateInfo(userInfo?: Authorize.UserInfo) {
    // await accountService.updateUser(updateUser)
    console.info(JSON.stringify(userInfo))
  }

  /**
   * 准备好
   */
  async ready() {
    Taro.showTabBar({ animation: false })

    if (this.props.onReady) {
      this.props.onReady()
    }
  }

  render() {
    const { isOpened, loading } = this.state

    return (
      <View
        className={classNames('auth-view', {
          'auth-view__show-auth': isOpened || loading,
        })}
      >
        {isOpened && (
          <Authorize onClickAuthorize={this.onClickAuthorize} miniProgramInfo={this.state.miniProgramInfo} />
        )}
        {this.props.children}
      </View>
    )
  }
}
